package org.someone.office;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VarUtil {

    public final static String defaultRegex = "\\$\\{[^{}]+\\}";    //正则表达式 匹配${...}

    /**
     * 根据map中的key、value替换字符串中的变量 变量格式${key}
     * @param strText
     * @param map
     * @return
     */
    public static String replaceText(String strText, Map<String, Object> map){
        String strValue = strText;
        if(strValue != null && isVar(strValue, defaultRegex)){
            String strdockey;
            int count = 0;
            while((strdockey = getVar(strValue, defaultRegex)) != null){
                String strmapkey = strdockey.substring(2,strdockey.length()-1);
                Object value = map.get(strmapkey);
                if(value instanceof List){  //如果是循环导出表
                    break;
                }else if(value == null && !map.containsKey(strmapkey)){
                    break;
                }else{
                    strValue = strValue.replace(strdockey, value != null ? value.toString() : "");
                }
                if(count++>100){break;}
            }
        }
        return strValue;
    }

    /**
     * 判断内容中是否有需替换的变量
     * @param strContent
     * @param strRegex
     * @return
     */
    public static boolean isVar(String strContent, String strRegex){
        Pattern pattern = Pattern.compile(strRegex);
        Matcher matcher = pattern.matcher(strContent);
        return matcher.find(0);
    }

    /**
     * 得到匹配的变量
     * @param strContent
     * @param strRegex
     * @return
     */
    public static String getVar(String strContent, String strRegex){
        String strvar = null;
        Pattern pattern = Pattern.compile(strRegex);
        Matcher matcher = pattern.matcher(strContent);
        if(matcher.find(0)){
            strvar = matcher.group();
        }
        return strvar;
    }

}
